package com.blue.service.impl;

import com.blue.dao.AccountDao;
import com.blue.dao.impl.AccountDaoImpl;
import com.blue.exceptions.MoneyNotEnoughException;
import com.blue.exceptions.TransferException;
import com.blue.pojo.Account;
import com.blue.service.AccountService;
import com.blue.utils.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

public class AccountServiceImpl implements AccountService {
    // private AccountDao dao = new AccountDaoImpl();
    private AccountDao dao = SqlSessionUtil.openSession().getMapper(AccountDao.class);

    @Override
    public void transfer(String fromActno, String toActno, Double money) throws MoneyNotEnoughException, TransferException {
        SqlSession sqlSession = SqlSessionUtil.openSession();

        // 判断转出账号的金额是否充足（select）
        Account fromAct = dao.selectByActno(fromActno);

        // 如果转出账户金额不足，提示用户
        if (fromAct.getBalance() < money) {
            throw new MoneyNotEnoughException("对不起, 转账账户余额不足!");
        }

        int count = 0;

        // 如果转出金额充足，更新转出账户余额（update）更新转入账户余额（update）
        Account toAct = dao.selectByActno(toActno);
        fromAct.setBalance(fromAct.getBalance() - money);
        toAct.setBalance(toAct.getBalance() + money);
        count += dao.updateByAct(toAct);
        count += dao.updateByAct(fromAct);

        if (count != 2) {
            throw new TransferException("转账异常, 未知原因!");
        }

        sqlSession.commit();
        SqlSessionUtil.close(sqlSession);
    }
}
